//@ts-nocheck
import React, { useState, useRef, useMemo, useEffect, Fragment } from 'react';
import { PullRefresh, Toast, Search } from 'react-vant';
import { Tag, Tabs, List } from 'antd-mobile';
import './style.less';
import './index.less';
import { Arrow, ArrowDown, Scan, ChartTrendingO } from '@react-vant/icons';
import { PlayOutline } from 'antd-mobile-icons';
import server from '@/utlis/server';
import jsonp from 'jsonp';
import { DemoBlock } from 'demos';
import Img from './images/蜡笔小新.jpg';
import Ygzdyx from './images/勇敢者的游戏.png';
import Bxqy from './images/冰雪奇缘.png';
import Lrcqa from './images/利刃出鞘.png';
import Nfczdjh from './images/南方车站的聚会.png';
import Th from './images/天火.png';
import Ws from './images/误杀.png';
import Dhb from './images/大红包.png';
import Ftfb from './images/反贪风暴4.png';
import { history } from 'umi';
import 'lib-flexible';
import '@/pages/golobo.less';

// const items = Array.from({ length: 3 }, (_, i) => i + 1)
export default function index() {
  const [errorMessage, setErrorMessage] = useState('');
  // 定位容器div
  let Location = useRef();
  let [currentLocation, setCurrentLocation] = useState('');
  // 获取经度
  let [lat, setLat] = useState();
  // 获取维度
  let [lon, setLon] = useState();
  // 获取省份
  let [province, setProvince] = useState('');
  // 获取城市
  let [city, setCity] = useState('');
  // 获取行政区
  let [district, setDistrict] = useState('');
  // 获取街道
  let [street, setStreet] = useState('');
  // 获取街道号
  let [streetNumber, setStreetNumber] = useState('');
  // 电影数据
  let [movieData, setMovieData] = useState([]);
  // 定位
  function showLocation() {
    let x = Location.current;

    //判断是否可以定位
    if (navigator.geolocation) {
      //getCurrentPosition()中需要传入一个回调函数
      navigator.geolocation.getCurrentPosition(location_1, showError, {
        enableHighAccuracy: true, // 位置是否精确获取
        timeout: 5000, //获取位置允许的最长时间
        maximumAge: 1000, // 多久更新获取一次位置
      });
    } else {
      x.innerHTML = '无法获取当前位置';
    }
  }
  function location_1(position) {
    setLon((lon = position.coords.longitude));
    setLat((lat = position.coords.latitude));

    // 显示获取到的用户定位中的纬度和经度
    // x.innerHTML = "纬度:" + position.coords.latitude + "经度:" + position.coords.longitude;
    // let lon = position.coords.longitude;
    var myGeo = new BMapGL.Geocoder();
    myGeo.getLocation(new BMapGL.Point(lon, lat), function (result) {
      if (result) {
        // console.log(result.addressComponents);
        // alert(JSON.stringify(result.addressComponents.province));
        setProvince((province = result.addressComponents.province));

        // localStorage.setItem('hkzf_city',JSON.stringify([{ "label": result.addressComponents.city, "value": "" }]))

        if (localStorage.getItem('click_city') != null) {
          let data = JSON.parse(localStorage.getItem('click_city'));
          setCity(data[0].label);
        } else {
          setCity((city = result.addressComponents.city));

          localStorage.setItem(
            'hkzf_city',
            JSON.stringify([
              { label: result.addressComponents.city, value: '' },
            ]),
          );
        }

        setDistrict((district = result.addressComponents.district));
        setStreet((street = result.addressComponents.street));
        setStreetNumber((streetNumber = result.addressComponents.streetNumber));
        // console.log(city);
        setCurrentLocation(
          (currentLocation = city + district + street + streetNumber),
        );
      }
    });
  }
  function showError(error) {
    //PERMISSION_DENIED 用户不允许地理定位
    //POSITON_UNAVAILABLE 无法获取当前位置
    let x = Location.current;
    //TIMEOUT 操作超时
    switch (error.code) {
      case error.PERMISSION_DENIED:
        setErrorMessage('用户未开启地理定位');
        break;
      case error.POSITON_UNAVAILABLE:
        setErrorMessage('无法获取当前位置');
        break;
      case error.TIMEOUT:
        setErrorMessage('操作超时');
        break;
    }
  }
  //跳转城市选择页面
  let dizhi = () => {
    history.push('/city');
  };

  //跳转电影详情页面
  let xiangqing = (Item) => {
    history.push({
      pathname: '/details',
      state: {
        _id: Item._id,
        Item,
      },
    });
  };

  //跳转购票页面
  let gp = (item) => {
    history.push({
      pathname: '/ticketing',
      state: {
        item: { paly_id: item },
      },
    });
  };

  const [value, setValue] = useState('');
  //下拉刷新页面
  const [count, setCount] = useState<number>(0);
  // 当前激活tbs
  let [activekey, setactivekey] = useState('1');
  // 影院数据
  let [moesdata, setmoesdata] = useState([]);
  // 即将上映数据
  let [newplays, setnewplays] = useState([]);
  // 在线观看数据
  let [previewsdata, setpreviewsdata] = useState([]);
  const onRefresh = (showToast) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (showToast) {
          Toast.info('刷新成功啦！');
        }
        setCount(count + 1);
        resolve(true);
      }, 1000);
    });
  };

  const shuaxin = () => {
    // console.log('刷新成功');
  };
  let getmoesdata = async () => {
    let { data } = await server.get('/getmovespaly', {
      params: {
        pagenation: 'nopagenation',
      },
    });
    // console.log(data.data);
    data.data.forEach((item) => {
      item.distance = 0;
    });
    setmoesdata(data.data);
  };

  let getmovieData = async () => {
    let { data } = await server.get('/getplays', {
      params: {
        pagenation: 'nopagenation',
      },
    });
    setMovieData(data.data);
  };

  // 即将上映数据
  let getnewplays = async () => {
    let { data } = await server.get('/getnewplays');
    setnewplays(data.data);
  };

  // 在线观看数据
  let getpreviewsdata = async () => {
    let { data } = await server.get('/getpreviews', {
      params: {
        pagenation: 'nopagenation',
      },
    });
    setpreviewsdata(data.data);
  };

  // 切换导航
  let activechange = (key) => {
    // console.log(key);
    if (key == '2') {
      getmoesdata();
    } else if (key == '3') {
      getnewplays();
    } else {
      getpreviewsdata();
    }
    setactivekey(key);
  };

  // 获取距离
  //   let getkm=(item,num)=>{
  //     let ddlon=item.lon.toFixed(6)
  //     let ddlat=item.lat.toFixed(6)

  //     let ak='7uIfaG0IpKfCuFNPGwX3KOXihxcgH3Mf'

  // jsonp(`https://api.map.baidu.com/directionlite/v1/driving?origin=${lat},${lon}&destination=${ddlon},${ddlat}&ak=${ak}`,null,async(err,state)=>{
  //   num+=state.result.routes[0].distance

  //   moesdata.forEach(c=>{
  //     if(c._id==item._id){
  //       c.distance=state.result.routes[0].distance
  //     }
  //   })
  //   setmoesdata([...moesdata])

  // })
  //   }

  useEffect(() => {
    showLocation();
    getmovieData();
  }, []);
  return (
    <div className="contexts" style={{ width: '100%', height: '100%' }}>
      {/* 下拉刷新 */}
      {/* <div
          className="demo-pull-refresh"
          style={{ width: '100vw', height: '1vh' }}
        >
          <Tabs>
            <PullRefresh
              successText="刷新成功啦！"
              onRefresh={() => onRefresh(false)}
            ></PullRefresh>
          </Tabs>
        </div> */}
      {/* 地址 */}
      <div
        className="citys"
        style={{
          width: '13rem',
          height: '1.1rem',
        }}
      >
        <div
          className="dizhi"
          style={{
            width: '1.4rem',
            height: '0.9rem',
            display: 'flex',
          }}
        >
          <div>
            <p
              ref={Location}
              className="bj"
              style={{
                width: '1.5rem',
                height: '1rem',
                fontSize: '0.35rem',
                marginTop: '0.2rem',
              }}
            >
              {city}
              <ArrowDown
                onClick={() => {
                  dizhi();
                }}
              />
            </p>
          </div>
          &nbsp;
          {/* 搜索 */}
          <div className="sear" style={{ width: '8rem', height: '1rem' }}>
            <Search
              shape="round"
              value={value}
              onChange={setValue}
              placeholder="搜影片丶影院丶演员丶资源..."
            />
          </div>
          &nbsp;
          {/* 扫码 */}
          <span style={{ fontSize: '0.8rem' }}>
            <Scan />
          </span>
        </div>
      </div>
      {/* 滚动标签页 */}

      <Tabs defaultActiveKey="1" activeKey={activekey} onChange={activechange}>
        <Tabs.Tab title="热映" key="1" destroyOnClose={true}>
          <div
            className="pf"
            style={{ width: '13rem', height: '1.1rem', marginTop: '0.5rem' }}
          >
            <div className="gh">
              <span style={{ fontSize: '0.8rem', textAlign: 'center' }}>
                <ChartTrendingO />
              </span>
              <p
                style={{
                  textAlign: 'center',
                  marginLeft: '-9rem',
                  marginTop: '-0.9rem',
                  fontSize: '0.5rem',
                }}
              >
                <b>实时票房</b>
              </p>
            </div>
            <div className="dp">
              今日大盘&nbsp;&nbsp;<p style={{ color: '#fb50ac' }}>4028.4万</p>
            </div>
          </div>
          <PullRefresh
            successText="刷新成功"
            onRefresh={() => onRefresh(false)}
            onRefreshEnd={() => shuaxin()}
          >
            <div
              className="contextss"
              style={{
                width: '13rem',
                height: '26rem',
                marginTop: '0.2rem',
                overflow: 'scroll',
              }}
            >
              {/* 下拉刷新 */}
              {/* <div
          className="demo-pull-refresh"
          style={{ width: '13rem', height: '1rem' }}
        >
          <Tabs>
            <PullRefresh
              successText="刷新成功啦！"
              onRefresh={() => onRefresh(false)}
            ></PullRefresh>
          </Tabs>
        </div> */}

              {/* 下拉刷新 */}
              <div
                className="demo-pull-refresh"
                style={{ width: '13rem', height: '1rem' }}
              >
                <Tabs>
                  <PullRefresh
                    successText="刷新成功啦！"
                    onRefresh={() => onRefresh(false)}
                  ></PullRefresh>
                </Tabs>

                {movieData.map((item, index) => {
                  return (
                    <Fragment key={item._id}>
                      <div className="conts">
                        <img
                          style={{
                            width: '2rem',
                            height: '2.3rem',
                            marginTop: '0.35rem',
                            borderRadius: '0.2rem',
                            marginLeft: '0.2rem',
                          }}
                          src={item.image}
                          alt=""
                          onClick={() => {
                            xiangqing(item);
                          }}
                        />
                        <div className="titles">
                          <h2
                            className="yg"
                            onClick={() => {
                              xiangqing();
                            }}
                          >
                            {item.name}
                          </h2>

                          {/* 介绍 */}
                          <div className="itemself">{item.self}</div>
                          <div
                            className="gp"
                            onClick={() => {
                              gp(item);
                            }}
                          >
                            <h3 className="gps" style={{ textAlign: 'center' }}>
                              购票
                            </h3>
                          </div>
                        </div>
                      </div>
                      <hr />
                    </Fragment>
                  );
                })}
              </div>
            </div>
          </PullRefresh>
        </Tabs.Tab>
        <Tabs.Tab title="影院" key="2" destroyOnClose={true}>
          <div className="moveryin">
            {moesdata.map((item, index) => {
              return (
                <div key={item._id} className="moveryin_zi">
                  <h5>
                    {item.name}{' '}
                    <span>
                      <b>{item.price}</b>元起
                    </span>
                  </h5>
                  <p>
                    {item.address}
                    {/* <span>{getkm(item,0)} {item.distance}</span> */}
                  </p>
                  <p>
                    {item.refund ? (
                      <Tag color="primary" fill="outline">
                        退票
                      </Tag>
                    ) : (
                      ''
                    )}
                    {item.ticket ? (
                      <Tag color="primary" fill="outline">
                        改签
                      </Tag>
                    ) : (
                      ''
                    )}
                    <Tag color="#87d068" fill="outline">
                      {item.language_id.name}
                    </Tag>
                    <Tag color="#87d068" fill="outline">
                      {item.version_id.name}
                    </Tag>
                    <Tag color="#87d068" fill="outline">
                      {item.palytype.name}
                    </Tag>
                  </p>
                </div>
              );
            })}
          </div>
        </Tabs.Tab>
        <Tabs.Tab title="即将上映" key="3" destroyOnClose={true}>
          <div className="newplay">
            {newplays.map((item) => {
              return (
                <div
                  key={item._id}
                  className="newplay_zi"
                  onClick={() => {
                    history.push({
                      pathname: '/details',
                      state: { _id: item._id },
                    });
                  }}
                >
                  <img src={item.image} alt="" />
                  <div className="newplay_name">
                    <h5>{item.name}</h5>
                    <p>{item.self}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </Tabs.Tab>
        <Tabs.Tab title="在线看" key="4" destroyOnClose={true}>
          <List>
            {previewsdata.map((item) => {
              return (
                <List.Item key={item._id}>
                  <div className="plre_box">
                    <img src={item.paly_id.image} alt="" />
                    <span
                      className="playicon_box"
                      // onClick={() => {
                      //   console.log(item);
                      // }}
                    >
                      <PlayOutline
                        onClick={() => {
                          // console.log(item);
                          history.push({
                            pathname: '/yugao',
                            state: { _id: item.paly_id._id },
                          });
                        }}
                      />
                    </span>
                    <div>
                      <h5>{item.paly_id.name}</h5>
                      <p>{item.paly_id.self}</p>
                    </div>
                  </div>
                </List.Item>
              );
            })}
          </List>
        </Tabs.Tab>
      </Tabs>
    </div>
  );
}
